package tacos.web.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.EntityModel;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.hateoas.CollectionModel;
import tacos.controller.DesignTacoController;
import tacos.domain.Taco;
import tacos.repository.TacoRepository;
import tacos.web.resources.TacoResource;
import tacos.web.resources.TacoResourceAssembler;

import java.util.List;
import java.util.Optional;

//@RestController  // 表明这是一个rest控制器,表示控制器中所有方法的返回值都要直接写入响应体中，而不是讲值放到模型中并传递给一个视图以便进行渲染
//@RequestMapping(path = "/design", produces = "application/json")
// 处理针对/design的请求，produces指明处理器方法只会处理Accept头信息包含"application/json"的请求
//@CrossOrigin(origins = "*")  // 允许跨域请求
public class DesignTacoApiController {
    private TacoRepository tacoRepository;

//    @Autowired
//    EntityLinks entityLinks;

    public DesignTacoApiController(TacoRepository tacoRepo) {
        this.tacoRepository = tacoRepo;
    }

//    @GetMapping("/recent")
//    public Iterable<Taco> recentTacos(){
//        PageRequest page = PageRequest.of(0,12, Sort.by("createdAt").descending());
//        // 得到12个最近创建的taco
//        return tacoRepository.findAll(page).getContent();
//    }

    @GetMapping("/recent")  // 为资源配置超链接
    public CollectionModel<TacoResource> recentTacos() {
        PageRequest page = PageRequest.of(0, 12, Sort.by("createdAt").descending());
        // 得到12个最近创建的taco
        List<Taco> tacos = tacoRepository.findAll(page).getContent();
        CollectionModel<TacoResource> tacoResources = new TacoResourceAssembler(DesignTacoApiController.class,TacoResource.class).toCollectionModel(tacos);

//        CollectionModel<EntityModel<Taco>> recentResources = new Co(tacoResources);
        //P148 为整体列表添加链接
//        recentResources.add(new Link("http://localhost:8080/design/recent", "recents"));  改造硬编码的URL
        /**
         * 1.向DesignTacoApiController获取 /design
         * 2.slash 添加 / 和 recent -> /design/recent
         * 3.指定连接存在的关系名
         */
//        recentResources.add(ControllerLinkBuilder.linkTo(DesignTacoApiController.class).slash("recent").withRel("recents"));
        /**
         * 使用methodOn 自动识别路径，去除掉任何硬编码的操作
         */
        /**
         * 这段代码会为整个列表添加上链接
         *     "_links": {
         *         "recents": {
         *             "href": "http://localhost:8080/design/recent"
         *         }
         *     }
          */
        tacoResources.add(linkTo(methodOn(DesignTacoApiController.class).recentTacos()).withRel("recents"));
        return tacoResources;
    }

    @GetMapping("/{id}")
    public ResponseEntity<Taco> tacoById(@PathVariable("id") Long id) {
        Optional<Taco> optTaco = tacoRepository.findById(id);
        /**
         *         if (optTaco.isPresent()){
         *             return new ResponseEntity<>(optTaco.get(), HttpStatus.OK);
         *         }
         *         return new ResponseEntity<>(null,HttpStatus.NOT_FOUND);
         */
        return optTaco.map(taco -> new ResponseEntity<>(taco, HttpStatus.OK)).orElseGet(() -> new ResponseEntity<>(null, HttpStatus.NOT_FOUND));
    }

    @PostMapping(consumes = "application/json")
    // consumes 指定请求输入（只会处理Content-type是application/json的请求）， produces 指定请求输出
    @ResponseStatus(HttpStatus.CREATED)  // 返回状态码201
    public Taco postTaco(@RequestBody Taco taco) {
        return tacoRepository.save(taco);
    }

}
